import React, { useLayoutEffect, useRef, useState } from "react";
import { useFormField } from "../../context/form-context";
import HtmlEditorLoader from "./HtmlEditorLoader";
import "./index.css";

let defaultConfig = {
  //这一批属性来源 tplData.form.data_control （步骤权限）
  // "code": "fuwenben",
  // "name": "富文本",
  // "type": "html_text",
  // "is_show": true,
  // "is_editable": true,
  // "is_required": false,

  //这一批属性来源 tplData.form.form_meta_data （表单设计器）
  // "isUsed": false,
  // "designProps": {
  //     "code": "fuwenben",
  //     "name": "富文本",
  //     "ui": "wfd_htmltext",
  //     "title": "富文本",
  //     "layout": "control_layout_leftRight",
  //     "defaultValue": "",
  //     "groupTitle": "",
  //     "byTableGroupTitle": false,
  //     "text": "",
  //     "tipstext": "",
  //     "type": "html_text",
  //     "title_w": 85
  // },

  //这一批属性来源 tplData.form.data_define （业务对象）
  // "show_type": "",
  // "show_type_name": "",
  // "props": {
  //     "source_type": "sql",
  //     "is_mobile_show": "show",
  //     "height": 300
  // },
  // "type_name": "HTML文本",
  
  //来源 tplData.form.defaultValueConf
  // "default": null
}

//富文本组件
export default function ({ field, label, rules, showLabel = true, cell,required, labelCol,isSubTableField, rowIndex, ...others }) {
  const { input , property, readonly, className ,isDisplay} = useFormField({ field, rules });
  const [width, setWidth] = useState();
  const wrapperRef = useRef();

  useLayoutEffect(() => {
    if (wrapperRef.current && wrapperRef.current.parentElement) {
      let styleWidthStr = wrapperRef.current.parentElement?.style?.width || "";
      let styleWidth = 0;
      if (~styleWidthStr?.indexOf("px")) {
        styleWidth = Number(styleWidthStr.replace("px", ""));
      }
      if (styleWidth > 0) {
        let currentWidth = wrapperRef.current.getBoundingClientRect().width;
        if (currentWidth > styleWidth) {
          setWidth(styleWidth + "px");
        }
      }
    }
  }, []);
  function getDataText(value) {
    return <div style={{ width: width }} className="inline-block w-full overflow-auto html-text" ref={wrapperRef} dangerouslySetInnerHTML={{ __html: value }}></div>;
  }
  if (isDisplay ||isSubTableField) {
    return input.value === undefined ? null : getDataText(input.value);
  }

  const component = <HtmlEditorLoader className={className} placeholder="请输入" {...input} cell={cell} disabled={property.disabled} {...others} {...readonly}></HtmlEditorLoader>;

  return component;
}
